package org.threads.banktransactions;

import java.util.concurrent.atomic.AtomicBoolean;

class Account implements Comparable {

    public static final String NOT_ENOUGH_MONEY_EX = "There is not enough money on account with id=";

    private AtomicBoolean atomicBoolean = new AtomicBoolean();

    private static int CURRENT_ID = 1;
    private int id;
    private volatile int amount;

    public Account(int amount) {
        setAmount(amount);
        setId(CURRENT_ID++);
    }

    public void withdraw(int amount) {

        if (amount > this.amount) {
            throw new IllegalArgumentException(NOT_ENOUGH_MONEY_EX + id);
        }

        setAmount(this.amount - amount);
    }

    public void deposit(int amount) {
        setAmount(this.amount + amount);
    }

    public int getAmount() {
        return amount;
    }

    public void setAmount(int amount) {

        this.amount = amount;
    }

    public void lock() {
        while (!atomicBoolean.compareAndSet(false, true)) {
        }
        ;
    }

    public void unlock() {
        atomicBoolean.set(false);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public int compareTo(Object o) {
        return getId() - ((Account) o).getId();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Account)) {
            return false;
        }

        Account account = (Account) o;

        if (id != account.id) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        return id;
    }
}
